/**
 * Node Http Method
 */

'use strict'
let koaRequest = require('koa-request')
let parse = require('co-body')

let HttpResponse = require('./httpResponse')
let cfg = require('../config/config')
let goDataConfig = cfg.goDataApi

// helps
function getCommonPath(originalUrl) {
    return `http://${goDataConfig.host}:${goDataConfig.basePort}${goDataConfig.basePath}${originalUrl}`
}
function getCommonConfig(opt) {
    return {
        body: opt.data && JSON.stringify(opt.data),
        method: opt.method || "GET",
        uri: opt.url,
        headers: {
            "Content-Type": 'application/json',
            // "Content-Type": 'application/x-www-form-urlencoded',
            "Content-Length": Buffer.byteLength(JSON.stringify(opt.data) || '', 'utf8'),
            "Cookie": opt.cookie || ''
        }
    }
}
module.exports = {
    httpRequest: function(opt) {
        opt = opt || {}
        opt.type = opt.type || 'GET'
        return function *(next) {
            let result = null
            let response = null
            let config = null
            let cookie = this.req.headers && this.req.headers.cookie
            let url = getCommonPath(this.originalUrl)

            // 设置config
            if(opt.type == 'GET' || opt.type == 'DELETE') {
                config = getCommonConfig({
                    url,
                    cookie
                })
            } else {
                let data = yield parse(this, { limit: '100kb' }) || null

                config = getCommonConfig({
                    url,
                    data,
                    cookie,
                    method: opt.type,
                })
            }

            // 发送请求
            if(opt.type === 'DELETE') {
                response = yield koaRequest.del(config)
            } else if(opt.type === 'PUT') {
                response = yield koaRequest.put(config)
            } else if(opt.type === 'POST') {
                response = yield koaRequest.post(config)
            } else if(opt.type === 'PATCH') {
                response = yield koaRequest.patch(config)
            } else if(opt.type === 'GET') {
                response = yield koaRequest(config)
            }
            console.log(url)
            console.log(config)
            console.log(response.body)
            console.log('>>>>>>')
            opt.callback && opt.callback.bind(this)(response)

            result = JSON.parse(response.body)
            HttpResponse(result, this)
            yield * next
        }
    }
}
